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.credit.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.SocieteCommonSQLElement;
19
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
20
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
21
import org.openconcerto.erp.core.common.ui.AbstractArticleItemTable;
22
import org.openconcerto.erp.core.common.ui.DeviseField;
23
import org.openconcerto.erp.core.common.ui.TotalPanel;
24
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
25
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
26
import org.openconcerto.erp.core.finance.payment.component.ModeDeReglementSQLComponent;
27
import org.openconcerto.erp.core.sales.credit.element.AvoirClientSQLElement;
28
import org.openconcerto.erp.core.sales.credit.ui.AvoirItemTable;
29
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
30
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
31
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
32
import org.openconcerto.erp.generationDoc.gestcomm.AvoirClientXmlSheet;
33
import org.openconcerto.erp.generationEcritures.GenerationMvtAvoirClient;
34
import org.openconcerto.erp.model.ISQLCompteSelector;
35
import org.openconcerto.erp.preferences.DefaultNXProps;
36
import org.openconcerto.sql.Configuration;
37
import org.openconcerto.sql.element.ElementSQLObject;
38
import org.openconcerto.sql.element.SQLElement;
39
import org.openconcerto.sql.model.SQLField;
40
import org.openconcerto.sql.model.SQLRow;
41
import org.openconcerto.sql.model.SQLRowAccessor;
42
import org.openconcerto.sql.model.SQLRowValues;
43
import org.openconcerto.sql.model.SQLSelect;
44
import org.openconcerto.sql.model.SQLTable;
45
import org.openconcerto.sql.model.Where;
46
import org.openconcerto.sql.sqlobject.ElementComboBox;
47
import org.openconcerto.sql.sqlobject.JUniqueTextField;
48
import org.openconcerto.sql.view.EditFrame;
49
import org.openconcerto.ui.DefaultGridBagConstraints;
25 ilm 50
import org.openconcerto.ui.FormLayouter;
18 ilm 51
import org.openconcerto.ui.JDate;
52
import org.openconcerto.ui.component.ITextArea;
53
import org.openconcerto.utils.ExceptionHandler;
21 ilm 54
import org.openconcerto.utils.checks.ValidState;
18 ilm 55
 
56
import java.awt.Dimension;
57
import java.awt.GridBagConstraints;
58
import java.awt.GridBagLayout;
59
import java.awt.event.ActionEvent;
60
import java.awt.event.ActionListener;
61
import java.beans.PropertyChangeEvent;
62
import java.beans.PropertyChangeListener;
63
import java.sql.SQLException;
19 ilm 64
import java.util.Arrays;
18 ilm 65
import java.util.Date;
66
import java.util.List;
67
 
68
import javax.swing.JCheckBox;
69
import javax.swing.JLabel;
19 ilm 70
import javax.swing.JOptionPane;
18 ilm 71
import javax.swing.JPanel;
72
import javax.swing.JScrollPane;
73
import javax.swing.JTextField;
74
import javax.swing.SwingConstants;
75
import javax.swing.SwingUtilities;
76
import javax.swing.event.DocumentEvent;
77
import javax.swing.event.DocumentListener;
78
 
79
import org.apache.commons.dbutils.handlers.ArrayListHandler;
80
 
81
public class AvoirClientSQLComponent extends TransfertBaseSQLComponent implements ActionListener {
82
 
83
    private JTextField textNom;
84
    private JDate date;
85
    private JUniqueTextField textNumero;
86
    private JCheckBox checkImpr, checkVisu;
87
    private AbstractArticleItemTable table;
88
    private JCheckBox boxAdeduire = new JCheckBox(getLabelFor("A_DEDUIRE"));
89
    private ElementSQLObject eltModeRegl;
90
    private final SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT");
91
    private final SQLElement clientElt = Configuration.getInstance().getDirectory().getElement(this.tableClient);
92
    private final ElementComboBox comboClient = new ElementComboBox();
93
    private ElementComboBox comboPole = new ElementComboBox();
94
    private ElementComboBox comboCommercial = new ElementComboBox();
95
    private ElementComboBox comboVerificateur = new ElementComboBox();
96
    private final ElementComboBox comboAdresse = new ElementComboBox();
97
    private final ElementComboBox comboBanque = new ElementComboBox();
98
    private JLabel labelCompteServ;
99
    private ISQLCompteSelector compteSelService;
100
    private static final SQLTable TABLE_PREFS_COMPTE = Configuration.getInstance().getBase().getTable("PREFS_COMPTE");
101
    private static final SQLRow ROW_PREFS_COMPTE = TABLE_PREFS_COMPTE.getRow(2);
102
 
103
    private SQLRowValues defaultContactRowValues;
104
 
105
    private JCheckBox checkCompteServiceAuto;
106
 
107
    private PropertyChangeListener listenerModeReglDefaut = new PropertyChangeListener() {
108
        public void propertyChange(PropertyChangeEvent arg0) {
109
            int idCli = AvoirClientSQLComponent.this.comboClient.getSelectedId();
110
            if (idCli > 1) {
111
                SQLRow rowCli = AvoirClientSQLComponent.this.tableClient.getRow(idCli);
112
                SQLElement sqleltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
113
                int idModeRegl = rowCli.getInt("ID_MODE_REGLEMENT");
114
                if (idModeRegl > 1 && AvoirClientSQLComponent.this.eltModeRegl.isCreated() && getMode() == Mode.INSERTION) {
115
                    SQLRow rowModeRegl = sqleltModeRegl.getTable().getRow(idModeRegl);
116
                    SQLRowValues rowValsModeRegl = rowModeRegl.createUpdateRow();
117
                    rowValsModeRegl.clearPrimaryKeys();
118
                    AvoirClientSQLComponent.this.eltModeRegl.setValue(rowValsModeRegl);
119
                }
120
            }
121
        }
122
    };
19 ilm 123
    private final ElementComboBox boxTarif = new ElementComboBox();
18 ilm 124
    private PropertyChangeListener changeClientListener = new PropertyChangeListener() {
125
        public void propertyChange(PropertyChangeEvent evt) {
126
            // compteSel.removeValueListener(changeCompteListener);
127
 
128
            if (AvoirClientSQLComponent.this.comboClient.getValue() != null) {
129
                Integer id = AvoirClientSQLComponent.this.comboClient.getValue();
130
                AvoirClientSQLComponent.this.defaultContactRowValues.put("ID_CLIENT", id);
131
                if (id > 1) {
132
                    SQLRow row = AvoirClientSQLComponent.this.clientElt.getTable().getRow(id);
133
 
19 ilm 134
                    if (comboClient.getElement().getTable().getFieldsName().contains("ID_TARIF")) {
135
 
136
                        // SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
137
                        // if (foreignRow.isUndefined() &&
138
                        // !row.getForeignRow("ID_DEVISE").isUndefined()) {
139
                        // SQLRowValues rowValsD = new SQLRowValues(foreignRow.getTable());
140
                        // rowValsD.put("ID_DEVISE", row.getObject("ID_DEVISE"));
141
                        // foreignRow = rowValsD;
142
                        //
143
                        // }
144
                        // tableBonItem.setTarif(foreignRow, true);
145
                        SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
146
                        if (!foreignRow.isUndefined() && (boxTarif.getSelectedRow() == null || boxTarif.getSelectedId() != foreignRow.getID())
147
                                && JOptionPane.showConfirmDialog(null, "Appliquer les tarifs associés au client?") == JOptionPane.YES_OPTION) {
148
                            boxTarif.setValue(foreignRow.getID());
149
                            // SaisieVenteFactureSQLComponent.this.tableFacture.setTarif(foreignRow,
150
                            // true);
151
                        } else {
152
                            boxTarif.setValue(foreignRow.getID());
153
                        }
154
                    }
155
 
18 ilm 156
                        Where w = new Where(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getKey(), "=", row.getInt("ID_ADRESSE"));
157
 
158
                        w = w.or(new Where(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getKey(), "=", row.getInt("ID_ADRESSE_L")));
159
                        w = w.or(new Where(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getKey(), "=", row.getInt("ID_ADRESSE_F")));
160
                        List<SQLRow> list = row.getReferentRows(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getField("ID_CLIENT"));
161
                        for (SQLRow row2 : list) {
162
                            w = w.or(new Where(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getKey(), "=", row2.getID()));
163
                        }
164
 
165
                        comboAdresse.getRequest().setWhere(w);
166
                } else {
167
                        comboAdresse.getRequest().setWhere(null);
168
                }
169
            }
170
        }
171
    };
172
 
173
 
174
    @Override
175
    protected SQLRowValues createDefaults() {
176
        SQLRowValues vals = new SQLRowValues(this.getTable());
177
        vals.put("A_DEDUIRE", Boolean.TRUE);
178
        this.eltModeRegl.setEditable(false);
179
        this.eltModeRegl.setCreated(false);
180
 
181
 
182
        // Selection du compte de service
183
        int idCompteVenteService = ROW_PREFS_COMPTE.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
184
        if (idCompteVenteService <= 1) {
185
            try {
186
                idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
187
            } catch (Exception e) {
188
                e.printStackTrace();
189
            }
190
        }
191
        vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(AvoirClientSQLElement.class));
192
        vals.put("MONTANT_TTC", Long.valueOf(0));
193
        vals.put("MONTANT_SERVICE", Long.valueOf(0));
194
        vals.put("MONTANT_HT", Long.valueOf(0));
195
        vals.put("MONTANT_TVA", Long.valueOf(0));
196
        vals.put("ID_COMPTE_PCE_SERVICE", idCompteVenteService);
197
 
198
        return vals;
199
    }
200
 
201
    public AvoirClientSQLComponent() {
202
        super(Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT"));
203
    }
204
 
205
    public void addViews() {
206
        this.setLayout(new GridBagLayout());
207
        final GridBagConstraints c = new DefaultGridBagConstraints();
208
 
25 ilm 209
        // Champ Module
210
        c.gridx = 0;
211
        c.gridy++;
212
        c.gridwidth = GridBagConstraints.REMAINDER;
213
        final JPanel addP = new JPanel();
214
        this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
215
        this.add(addP, c);
216
 
217
        c.gridy++;
218
        c.gridwidth = 1;
219
 
18 ilm 220
        this.textNom = new JTextField();
221
        this.date = new JDate(true);
222
        this.date.addValueListener(new PropertyChangeListener() {
223
 
224
            @Override
225
            public void propertyChange(PropertyChangeEvent evt) {
226
                fireValidChange();
227
 
228
            }
229
        });
230
        this.comboClient.addValueListener(this.listenerModeReglDefaut);
231
        this.comboClient.addValueListener(this.changeClientListener);
232
 
233
        // Ligne 1: Numero
234
        this.add(new JLabel(getLabelFor("NUMERO"), SwingConstants.RIGHT), c);
235
        c.weightx = 1;
236
        c.fill = GridBagConstraints.NONE;
237
        c.gridx++;
238
        textNumero = new JUniqueTextField(16);
239
        DefaultGridBagConstraints.lockMinimumSize(textNumero);
240
        this.add(this.textNumero, c);
241
 
242
        // Date
243
        c.gridx++;
244
        c.weightx = 0;
245
        c.fill = GridBagConstraints.HORIZONTAL;
246
        this.add(new JLabel("Date", SwingConstants.RIGHT), c);
247
        c.gridx++;
248
        c.weightx = 1;
249
        c.fill = GridBagConstraints.NONE;
250
        this.add(this.date, c);
251
 
252
        // Ligne 2: Libellé
253
        c.gridx = 0;
254
        c.gridy++;
255
        c.weightx = 0;
256
        c.fill = GridBagConstraints.HORIZONTAL;
257
        this.add(new JLabel(getLabelFor("NOM"), SwingConstants.RIGHT), c);
258
        c.gridx++;
259
        // c.weightx = 1;
260
        this.add(this.textNom, c);
261
 
262
        // Commercial
263
        c.gridx++;
264
        c.fill = GridBagConstraints.HORIZONTAL;
265
        c.weightx = 0;
266
        this.add(new JLabel(getLabelFor("ID_COMMERCIAL"), SwingConstants.RIGHT), c);
267
        c.gridx++;
268
        // c.weightx = 1;
269
        c.fill = GridBagConstraints.NONE;
270
        this.comboCommercial = new ElementComboBox();
271
        this.comboCommercial.setMinimumSize(this.comboCommercial.getPreferredSize());
272
        this.add(this.comboCommercial, c);
273
 
274
        this.addSQLObject(this.comboCommercial, "ID_COMMERCIAL");
275
 
276
        // Ligne 3: Motif
277
        c.fill = GridBagConstraints.HORIZONTAL;
278
        c.gridx = 0;
279
        c.gridy++;
280
        c.weightx = 0;
281
        this.add(new JLabel(getLabelFor("MOTIF"), SwingConstants.RIGHT), c);
282
        c.gridx++;
283
        c.gridwidth = 3;
284
        // c.weightx = 1;
285
 
286
        JTextField textMotif = new JTextField();
287
        this.add(textMotif, c);
288
 
289
        // Client
290
        c.gridx = 0;
291
        c.gridy++;
292
        // c.weightx = 0;
293
        c.gridwidth = 1;
294
        this.add(new JLabel(getLabelFor("ID_CLIENT"), SwingConstants.RIGHT), c);
295
        c.gridx++;
296
        c.gridwidth = 3;
297
        // c.weightx = 1;
298
        c.fill = GridBagConstraints.NONE;
299
        this.add(this.comboClient, c);
300
            // Adresse spe
301
            c.gridx = 0;
302
            c.gridy++;
303
            c.fill = GridBagConstraints.HORIZONTAL;
304
            // c.weightx = 0;
305
            c.gridwidth = 1;
306
            this.add(new JLabel(getLabelFor("ID_ADRESSE"), SwingConstants.RIGHT), c);
307
 
308
            c.gridx++;
309
            c.gridwidth = 3;
310
            // c.weightx = 1;
311
            c.fill = GridBagConstraints.NONE;
312
            this.add(this.comboAdresse, c);
313
        final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
314
 
315
        // Contact
316
        c.gridx = 0;
317
        c.gridy++;
318
        c.gridwidth = 1;
319
        c.fill = GridBagConstraints.HORIZONTAL;
320
        // c.weightx = 0;
321
        final JLabel labelContact = new JLabel(getLabelFor("ID_CONTACT"), SwingConstants.RIGHT);
322
        this.add(labelContact, c);
323
 
324
        c.gridx++;
325
        c.gridwidth = 3;
326
        // c.weightx = 1;
327
        c.fill = GridBagConstraints.NONE;
328
        final ElementComboBox selectContact = new ElementComboBox();
329
        this.add(selectContact, c);
330
 
331
        this.addView(selectContact, "ID_CONTACT");
332
        this.defaultContactRowValues = new SQLRowValues(selectContact.getRequest().getPrimaryTable());
333
        selectContact.getAddComp().setDefaults(this.defaultContactRowValues);
334
 
335
 
336
 
337
        // Compte Service
338
        this.checkCompteServiceAuto = new JCheckBox(getLabelFor("COMPTE_SERVICE_AUTO"));
339
        this.addSQLObject(this.checkCompteServiceAuto, "COMPTE_SERVICE_AUTO");
340
        this.compteSelService = new ISQLCompteSelector();
341
 
342
        this.labelCompteServ = new JLabel("Compte Service");
343
        c.gridy++;
344
        c.gridx = 0;
345
        c.gridwidth = 1;
346
        // c.weightx = 0;
347
        this.labelCompteServ.setHorizontalAlignment(SwingConstants.RIGHT);
348
        this.add(this.labelCompteServ, c);
349
 
350
        c.gridx++;
351
        c.gridwidth = GridBagConstraints.REMAINDER;
352
        // c.weightx = 1;
353
        this.add(this.compteSelService, c);
354
 
355
        this.addRequiredSQLObject(this.compteSelService, "ID_COMPTE_PCE_SERVICE");
356
 
357
        String valServ = DefaultNXProps.getInstance().getStringProperty("ArticleService");
358
        Boolean bServ = Boolean.valueOf(valServ);
359
        if (!bServ) {
360
            this.labelCompteServ.setVisible(false);
361
            this.compteSelService.setVisible(false);
362
        }
363
 
364
        this.checkCompteServiceAuto.addActionListener(new ActionListener() {
365
            @Override
366
            public void actionPerformed(ActionEvent e) {
367
                setCompteServiceVisible(!AvoirClientSQLComponent.this.checkCompteServiceAuto.isSelected());
368
            }
369
        });
370
 
371
        // setCompteServiceVisible(!(bServ != null && !bServ.booleanValue()));
372
 
373
 
19 ilm 374
        // Tarif
375
        if (this.getTable().getFieldsName().contains("ID_TARIF")) {
376
            // TARIF
377
            c.gridy++;
378
            c.gridx = 0;
379
            c.weightx = 0;
380
            c.weighty = 0;
381
            c.gridwidth = 1;
382
            this.add(new JLabel("Tarif à appliquer"), c);
383
            c.gridx++;
384
            c.gridwidth = GridBagConstraints.REMAINDER;
385
 
386
            c.weightx = 1;
387
            this.add(boxTarif, c);
388
            this.addView(boxTarif, "ID_TARIF");
389
            boxTarif.addValueListener(new PropertyChangeListener() {
390
 
391
                @Override
392
                public void propertyChange(PropertyChangeEvent evt) {
393
                    table.setTarif(boxTarif.getSelectedRow(), false);
394
                }
395
            });
396
        }
397
 
18 ilm 398
        // Table
399
            this.table = new AvoirItemTable();
400
        c.gridx = 0;
401
        c.gridy++;
402
        c.fill = GridBagConstraints.BOTH;
403
        c.gridheight = 1;
404
        c.gridwidth = GridBagConstraints.REMAINDER;
405
        c.weighty = 1;
406
        // c.weightx = 0;
407
        this.add(this.table, c);
408
        this.addView(this.table.getRowValuesTable(), "");
409
 
410
        // Panel du bas
411
        final JPanel panelBottom = getBottomPanel();
412
        c.gridy++;
413
        c.weighty = 0;
414
        this.add(panelBottom, c);
415
 
416
        // Infos
417
 
418
        c.gridheight = 1;
419
        c.gridx = 0;
420
        c.gridy++;
421
        this.add(new JLabel(getLabelFor("INFOS")), c);
422
 
423
        c.gridy++;
424
        c.fill = GridBagConstraints.BOTH;
425
        c.weighty = 0;
426
        c.gridwidth = 4;
427
        ITextArea infos = new ITextArea(4, 4);
428
        JScrollPane scrollPane = new JScrollPane(infos);
429
        DefaultGridBagConstraints.lockMinimumSize(scrollPane);
430
        this.add(scrollPane, c);
431
 
432
        //
433
        // Impression
434
        JPanel panelGestDoc = new JPanel();
435
 
436
        this.checkImpr = new JCheckBox("Imprimer");
437
        this.checkVisu = new JCheckBox("Visualiser");
438
        panelGestDoc.add(this.checkImpr);
439
        panelGestDoc.add(this.checkVisu);
440
        c.fill = GridBagConstraints.NONE;
441
        c.gridy++;
442
        c.anchor = GridBagConstraints.EAST;
443
        this.add(panelGestDoc, c);
444
 
445
        this.addSQLObject(this.textNom, "NOM");
446
        this.addSQLObject(this.boxAdeduire, "A_DEDUIRE");
447
        this.addSQLObject(textMotif, "MOTIF");
448
            this.addSQLObject(this.comboAdresse, "ID_ADRESSE");
449
 
450
        this.addRequiredSQLObject(this.textNumero, "NUMERO");
451
        this.addRequiredSQLObject(this.date, "DATE");
452
        this.addRequiredSQLObject(this.comboClient, "ID_CLIENT");
453
 
454
        this.boxAdeduire.addActionListener(this);
455
 
456
        DefaultGridBagConstraints.lockMinimumSize(comboClient);
457
        DefaultGridBagConstraints.lockMinimumSize(this.comboAdresse);
458
        DefaultGridBagConstraints.lockMinimumSize(this.comboBanque);
459
        DefaultGridBagConstraints.lockMinimumSize(comboCommercial);
460
 
461
    }
462
 
463
    private JPanel getBottomPanel() {
464
 
465
        // UI
466
 
467
        final JPanel panel = new JPanel(new GridBagLayout());
468
        panel.setOpaque(false);
469
        final GridBagConstraints c = new DefaultGridBagConstraints();
470
        c.anchor = GridBagConstraints.NORTHWEST;
471
        c.weightx = 1;
472
        // Colonne 1
473
        this.boxAdeduire.setOpaque(false);
474
        this.boxAdeduire.setMinimumSize(new Dimension(430, this.boxAdeduire.getPreferredSize().height));
475
        this.boxAdeduire.setPreferredSize(new Dimension(430, this.boxAdeduire.getPreferredSize().height));
476
        panel.add(this.boxAdeduire, c);
477
        this.addView("ID_MODE_REGLEMENT", DEC + ";" + SEP);
478
        this.eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT");
479
 
480
        c.gridy++;
481
        c.fill = GridBagConstraints.NONE;
482
        c.weighty = 1;
483
        this.eltModeRegl.setOpaque(false);
484
        panel.add(this.eltModeRegl, c);
485
 
486
        // Colonne 2 : port et remise
487
 
488
        final JPanel panelPortEtRemise = new JPanel();
489
        panelPortEtRemise.setOpaque(false);
490
        panelPortEtRemise.setLayout(new GridBagLayout());
491
 
492
        final GridBagConstraints cFrais = new DefaultGridBagConstraints();
493
 
494
        DeviseField textPortHT = new DeviseField(5);
495
        DeviseField textRemiseHT = new DeviseField(5);
496
 
497
        // Frais de port
498
        cFrais.gridheight = 1;
499
        cFrais.fill = GridBagConstraints.VERTICAL;
500
        cFrais.weighty = 1;
501
        cFrais.gridx = 1;
502
 
503
        JLabel labelPortHT = new JLabel(getLabelFor("PORT_HT"));
504
        labelPortHT.setHorizontalAlignment(SwingConstants.RIGHT);
505
        cFrais.gridy++;
506
        panelPortEtRemise.add(labelPortHT, cFrais);
507
        cFrais.gridx++;
508
        DefaultGridBagConstraints.lockMinimumSize(textPortHT);
509
        panelPortEtRemise.add(textPortHT, cFrais);
510
 
511
        // Remise
512
        JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
513
        labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
514
        cFrais.gridy++;
515
        cFrais.gridx = 1;
516
        panelPortEtRemise.add(labelRemiseHT, cFrais);
517
        cFrais.gridx++;
518
        DefaultGridBagConstraints.lockMinimumSize(textRemiseHT);
519
        panelPortEtRemise.add(textRemiseHT, cFrais);
520
        cFrais.gridy++;
521
 
522
        c.gridx++;
523
        c.gridy = 0;
524
        c.gridheight = 2;
525
        c.weightx = 0;
526
        c.fill = GridBagConstraints.HORIZONTAL;
527
        c.anchor = GridBagConstraints.NORTHWEST;
528
        panel.add(panelPortEtRemise, c);
529
 
530
        // Colonne 3 : totaux
531
        final DeviseField fieldHT = new DeviseField();
532
        final DeviseField fieldTVA = new DeviseField();
533
        final DeviseField fieldService = new DeviseField();
534
        final DeviseField fieldTTC = new DeviseField();
535
        // SQL
536
        addSQLObject(textPortHT, "PORT_HT");
19 ilm 537
        final DeviseField fieldDevise = new DeviseField();
538
        if (getTable().getFieldsName().contains("T_DEVISE"))
539
            addSQLObject(fieldDevise, "T_DEVISE");
18 ilm 540
        addSQLObject(textRemiseHT, "REMISE_HT");
541
        addRequiredSQLObject(fieldHT, "MONTANT_HT");
542
        addRequiredSQLObject(fieldTVA, "MONTANT_TVA");
543
        addRequiredSQLObject(fieldTTC, "MONTANT_TTC");
544
        addRequiredSQLObject(fieldService, "MONTANT_SERVICE");
545
        //
19 ilm 546
        JTextField poids = new JTextField();
547
        if (getTable().getFieldsName().contains("T_POIDS"))
548
            addSQLObject(poids, "T_POIDS");
549
        final TotalPanel totalTTC = new TotalPanel(this.table.getRowValuesTable(), this.table.getPrixTotalHTElement(), this.table.getPrixTotalTTCElement(), this.table.getHaElement(),
550
                this.table.getQteElement(), fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, this.table.getPrixServiceElement(), fieldDevise,
551
                this.table.getTableElementTotalDevise(), poids, this.table.getPoidsTotalElement());
18 ilm 552
        totalTTC.setOpaque(false);
553
        c.gridx++;
554
        c.gridy = 0;
555
        c.gridheight = 2;
556
        c.fill = GridBagConstraints.BOTH;
557
        panel.add(totalTTC, c);
558
 
559
        // Listeners
560
        textPortHT.getDocument().addDocumentListener(new DocumentListener() {
561
            public void changedUpdate(DocumentEvent e) {
562
                totalTTC.updateTotal();
563
            }
564
 
565
            public void removeUpdate(DocumentEvent e) {
566
                totalTTC.updateTotal();
567
            }
568
 
569
            public void insertUpdate(DocumentEvent e) {
570
                totalTTC.updateTotal();
571
            }
572
        });
573
 
574
        textRemiseHT.getDocument().addDocumentListener(new DocumentListener() {
575
            public void changedUpdate(DocumentEvent e) {
576
                totalTTC.updateTotal();
577
            }
578
 
579
            public void removeUpdate(DocumentEvent e) {
580
                totalTTC.updateTotal();
581
            }
582
 
583
            public void insertUpdate(DocumentEvent e) {
584
                totalTTC.updateTotal();
585
            }
586
        });
587
        return panel;
588
    }
589
 
21 ilm 590
    @Override
591
    public synchronized ValidState getValidState() {
592
        final ValidState selfState;
18 ilm 593
        final Date value = this.date.getValue();
21 ilm 594
        if (value != null && value.after(SocieteCommonSQLElement.getDateDebutExercice())) {
595
            selfState = ValidState.getTrueInstance();
596
        } else {
597
            selfState = ValidState.createCached(false, "La date est incorrecte, cette période est cloturée.");
598
        }
599
        return super.getValidState().and(selfState);
18 ilm 600
    }
601
 
602
    private void setCompteServiceVisible(boolean b) {
603
        this.compteSelService.setVisible(b);
604
        this.labelCompteServ.setVisible(b);
605
    }
606
 
607
    private String getInitialesFromVerif(SQLRow row) {
608
        String s = "";
609
 
610
        if (row != null) {
611
            String prenom = row.getString("PRENOM");
612
            if (prenom != null && prenom.length() > 0) {
613
                s += prenom.toUpperCase().charAt(0);
614
            }
615
            String nom = row.getString("NOM");
616
            if (nom != null && nom.length() > 0) {
617
                s += nom.toUpperCase().charAt(0);
618
            }
619
        }
620
 
621
        return s;
622
    }
623
 
624
    private void createCompteServiceAuto(int id) {
625
        SQLRow rowPole = this.comboPole.getSelectedRow();
626
        SQLRow rowVerif = this.comboVerificateur.getSelectedRow();
627
        String verifInitiale = getInitialesFromVerif(rowVerif);
628
        int idCpt = ComptePCESQLElement.getId("706" + rowPole.getString("CODE") + verifInitiale, "Service " + rowPole.getString("NOM") + " " + rowVerif.getString("NOM"));
629
        SQLRowValues rowVals = this.getTable().getRow(id).createEmptyUpdateRow();
630
        rowVals.put("ID_COMPTE_PCE_SERVICE", idCpt);
631
        try {
632
            rowVals.update();
633
        } catch (SQLException e) {
634
            e.printStackTrace();
635
        }
636
    }
637
 
638
    @Override
639
    public int insert(SQLRow order) {
640
 
641
        int id = getSelectedID();
642
        final SQLTable tableNum = this.getTable().getBase().getTable("NUMEROTATION_AUTO");
643
        if (this.textNumero.checkValidation()) {
644
 
645
            id = super.insert(order);
646
            this.table.updateField("ID_AVOIR_CLIENT", id);
647
 
648
            // incrémentation du numéro auto
649
            if (NumerotationAutoSQLElement.getNextNumero(AvoirClientSQLElement.class).equalsIgnoreCase(this.textNumero.getText().trim())) {
650
                SQLRowValues rowVals = new SQLRowValues(tableNum);
651
                int val = tableNum.getRow(2).getInt("AVOIR_START");
652
                val++;
653
                rowVals.put("AVOIR_START", Integer.valueOf(val));
654
 
655
                try {
656
                    rowVals.update(2);
657
                } catch (SQLException e) {
658
 
659
                    e.printStackTrace();
660
                }
661
            }
662
 
663
            final SQLRow row = getTable().getRow(id);
664
            SQLRowValues rowVals2 = row.createUpdateRow();
665
            Long l = rowVals2.getLong("MONTANT_SOLDE");
666
            Long l2 = rowVals2.getLong("MONTANT_TTC");
667
 
668
            rowVals2.put("MONTANT_RESTANT", l2 - l);
669
 
670
            try {
671
                rowVals2.update();
672
            } catch (SQLException e) {
673
                // TODO Auto-generated catch block
674
                e.printStackTrace();
675
            }
676
 
677
            updateStock(id);
678
 
679
            GenerationMvtAvoirClient gen = new GenerationMvtAvoirClient(id);
680
            gen.genereMouvement();
681
 
682
            // generation du document
25 ilm 683
            createAvoirClient(row);
18 ilm 684
 
685
        } else {
686
            ExceptionHandler.handle("Impossible de modifier, numéro d'avoir existant.");
687
            Object root = SwingUtilities.getRoot(this);
688
            if (root instanceof EditFrame) {
689
                EditFrame frame = (EditFrame) root;
690
                frame.getPanel().setAlwaysVisible(true);
691
            }
692
        }
693
        return id;
694
    }
695
 
25 ilm 696
    private void createAvoirClient(final SQLRow row) {
697
 
698
        final AvoirClientXmlSheet bSheet = new AvoirClientXmlSheet(row);
699
        try {
700
            bSheet.createDocumentAsynchronous();
701
            bSheet.showPrintAndExportAsynchronous(checkVisu.isSelected(), checkImpr.isSelected(), true);
702
        } catch (Exception e) {
703
            ExceptionHandler.handle("Impossible de créer l'avoir", e);
704
        }
705
 
706
    }
707
 
18 ilm 708
    @Override
709
    public void select(SQLRowAccessor r) {
710
        if (r != null) {
711
            this.textNumero.setIdSelected(r.getID());
712
        }
713
        this.comboClient.rmValueListener(listenerModeReglDefaut);
714
        this.comboClient.rmValueListener(changeClientListener);
715
 
716
        if (r != null) {
717
            this.table.insertFrom("ID_AVOIR_CLIENT", r.getID());
718
 
719
            // Les contacts sont filtrés en fonction du client (ID_AFFAIRE.ID_CLIENT), donc si
720
            // l'ID_CONTACT est changé avant ID_AFFAIRE le contact ne sera pas présent dans la combo
721
            // => charge en deux fois les valeurs
722
            final SQLRowValues rVals = r.asRowValues();
723
            final SQLRowValues vals = new SQLRowValues(r.getTable());
724
 
725
            vals.load(rVals, createSet("ID_CLIENT"));
726
            // vals a besoin de l'ID sinon incohérence entre ID_AFFAIRE et ID (eg for
727
            // reloadTable())
728
            // ne pas supprimer l'ID de rVals pour qu'on puisse UPDATE
729
            vals.setID(rVals.getID());
730
            super.select(vals);
731
            rVals.remove("ID_CLIENT");
732
            super.select(rVals);
733
        } else {
734
            super.select(r);
735
        }
736
        this.comboClient.addValueListener(listenerModeReglDefaut);
737
        this.comboClient.addValueListener(changeClientListener);
738
    }
739
 
740
    @Override
741
    public void update() {
742
        if (this.textNumero.checkValidation()) {
743
            super.update();
744
            this.table.updateField("ID_AVOIR_CLIENT", getSelectedID());
745
 
746
            // On efface les anciens mouvements de stocks
747
            SQLRow row = getTable().getRow(getSelectedID());
748
            SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
749
            SQLSelect sel = new SQLSelect(eltMvtStock.getTable().getBase());
750
            sel.addSelect(eltMvtStock.getTable().getField("ID"));
751
            Where w = new Where(eltMvtStock.getTable().getField("IDSOURCE"), "=", row.getID());
752
            Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
753
            sel.setWhere(w.and(w2));
754
 
755
            List l = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
756
            if (l != null) {
757
                for (int i = 0; i < l.size(); i++) {
758
                    Object[] tmp = (Object[]) l.get(i);
759
                    try {
760
                        eltMvtStock.archive(((Number) tmp[0]).intValue());
761
                    } catch (SQLException e) {
762
                        e.printStackTrace();
763
                    }
764
                }
765
            }
766
 
767
            SQLRowValues rowVals2 = getTable().getRow(getSelectedID()).createUpdateRow();
768
            Long l2 = rowVals2.getLong("MONTANT_SOLDE");
769
            Long l3 = rowVals2.getLong("MONTANT_TTC");
770
 
771
            rowVals2.put("MONTANT_RESTANT", l3 - l2);
772
 
773
            try {
774
                rowVals2.update();
775
            } catch (SQLException e) {
776
                // TODO Auto-generated catch block
777
                e.printStackTrace();
778
            }
779
 
780
            // On met à jour le stock
781
            updateStock(getSelectedID());
782
 
783
            int idMvt = row.getInt("ID_MOUVEMENT");
784
 
785
            // on supprime tout ce qui est lié à la facture d'avoir
786
            System.err.println("Archivage des fils");
787
            EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE");
788
            eltEcr.archiveMouvementProfondeur(idMvt, false);
789
 
790
            GenerationMvtAvoirClient gen = new GenerationMvtAvoirClient(getSelectedID(), idMvt);
791
            gen.genereMouvement();
792
 
25 ilm 793
            createAvoirClient(row);
18 ilm 794
        } else {
795
            ExceptionHandler.handle("Impossible de modifier, numéro d'avoir existant.");
796
            Object root = SwingUtilities.getRoot(this);
797
            if (root instanceof EditFrame) {
798
                EditFrame frame = (EditFrame) root;
799
                frame.getPanel().setAlwaysVisible(true);
800
            }
801
            return;
802
        }
803
    }
804
 
805
    public void loadFactureItem(int idFacture) {
806
 
807
        SQLElement facture = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
808
        SQLElement factureElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
809
 
810
        loadItem(this.table, facture, idFacture, factureElt);
811
 
812
    }
813
 
814
    /**
815
     * Mise à jour des stocks pour chaque article composant la facture d'avoir
816
     */
817
    private void updateStock(int id) {
818
 
819
        SQLElement eltArticleAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT_ELEMENT");
820
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
821
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
822
        SQLRow rowAvoir = getTable().getRow(id);
823
 
824
        // On récupére les articles qui composent la facture
825
        SQLSelect selEltAvoir = new SQLSelect(eltArticleAvoir.getTable().getBase());
826
        selEltAvoir.addSelect(eltArticleAvoir.getTable().getField("ID"));
827
        selEltAvoir.setWhere(new Where(eltArticleAvoir.getTable().getField("ID_AVOIR_CLIENT"), "=", id));
828
 
829
        List lEltAvoir = (List) eltArticleAvoir.getTable().getBase().getDataSource().execute(selEltAvoir.asString(), new ArrayListHandler());
830
 
831
        if (lEltAvoir != null) {
832
            for (int i = 0; i < lEltAvoir.size(); i++) {
833
 
834
                // Elt qui compose facture
835
                Object[] tmp = (Object[]) lEltAvoir.get(i);
836
                int idEltFact = ((Number) tmp[0]).intValue();
837
                SQLRow rowEltAvoir = eltArticleAvoir.getTable().getRow(idEltFact);
838
 
839
                // on récupére l'article qui lui correspond
840
                SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
841
                for (SQLField field : eltArticle.getTable().getFields()) {
842
                    if (rowEltAvoir.getTable().getFieldsName().contains(field.getName())) {
843
                        rowArticle.put(field.getName(), rowEltAvoir.getObject(field.getName()));
844
                    }
845
                }
846
                // rowArticle.loadAllSafe(rowEltFact);
847
                int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
848
 
849
                // on crée un mouvement de stock pour chacun des articles
850
                SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
851
                SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
852
                rowVals.put("QTE", rowEltAvoir.getInt("QTE"));
853
                rowVals.put("NOM", "Avoir client N°" + rowAvoir.getString("NUMERO"));
854
                rowVals.put("IDSOURCE", id);
855
                rowVals.put("SOURCE", getTable().getName());
856
                rowVals.put("ID_ARTICLE", idArticle);
857
                rowVals.put("DATE", rowAvoir.getObject("DATE"));
858
                try {
859
                    SQLRow row = rowVals.insert();
19 ilm 860
                    MouvementStockSQLElement.updateStock(Arrays.asList(row.getID()));
18 ilm 861
                } catch (SQLException e) {
862
                    e.printStackTrace();
863
                }
25 ilm 864
 
18 ilm 865
            }
866
        }
867
    }
868
 
869
    public void actionPerformed(ActionEvent e) {
870
        if (e.getSource() == this.boxAdeduire) {
871
            if (this.eltModeRegl != null) {
872
                this.eltModeRegl.setEditable(!this.boxAdeduire.isSelected());
873
                this.eltModeRegl.setCreated(!this.boxAdeduire.isSelected());
874
            }
875
        }
876
    }
877
}