OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
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;
93 ilm 17
 
18 ilm 18
import org.openconcerto.erp.config.ComptaPropsConfiguration;
19
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
83 ilm 20
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
63 ilm 21
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
18 ilm 22
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
156 ilm 23
import org.openconcerto.erp.core.common.element.SocieteCommonSQLElement;
18 ilm 24
import org.openconcerto.erp.core.common.ui.AbstractArticleItemTable;
25
import org.openconcerto.erp.core.common.ui.DeviseField;
132 ilm 26
import org.openconcerto.erp.core.common.ui.PanelFrame;
18 ilm 27
import org.openconcerto.erp.core.common.ui.TotalPanel;
93 ilm 28
import org.openconcerto.erp.core.customerrelationship.customer.ui.AddressChoiceUI;
29
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
174 ilm 30
import org.openconcerto.erp.core.customerrelationship.customer.ui.CategorieComptableChoiceUI;
18 ilm 31
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
32
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
33
import org.openconcerto.erp.core.finance.payment.component.ModeDeReglementSQLComponent;
34
import org.openconcerto.erp.core.sales.credit.ui.AvoirItemTable;
132 ilm 35
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
36
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
37
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
18 ilm 38
import org.openconcerto.erp.generationDoc.gestcomm.AvoirClientXmlSheet;
39
import org.openconcerto.erp.generationEcritures.GenerationMvtAvoirClient;
132 ilm 40
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
18 ilm 41
import org.openconcerto.erp.model.ISQLCompteSelector;
73 ilm 42
import org.openconcerto.erp.panel.PanelOOSQLComponent;
18 ilm 43
import org.openconcerto.erp.preferences.DefaultNXProps;
93 ilm 44
import org.openconcerto.erp.preferences.GestionClientPreferencePanel;
94 ilm 45
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
18 ilm 46
import org.openconcerto.sql.Configuration;
47
import org.openconcerto.sql.element.ElementSQLObject;
142 ilm 48
import org.openconcerto.sql.element.SQLComponent;
18 ilm 49
import org.openconcerto.sql.element.SQLElement;
73 ilm 50
import org.openconcerto.sql.model.SQLField;
18 ilm 51
import org.openconcerto.sql.model.SQLRow;
52
import org.openconcerto.sql.model.SQLRowAccessor;
53
import org.openconcerto.sql.model.SQLRowValues;
54
import org.openconcerto.sql.model.SQLSelect;
55
import org.openconcerto.sql.model.SQLTable;
56
import org.openconcerto.sql.model.Where;
93 ilm 57
import org.openconcerto.sql.preferences.SQLPreferences;
132 ilm 58
import org.openconcerto.sql.request.ComboSQLRequest;
18 ilm 59
import org.openconcerto.sql.sqlobject.ElementComboBox;
60
import org.openconcerto.sql.sqlobject.JUniqueTextField;
132 ilm 61
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
156 ilm 62
import org.openconcerto.sql.users.rights.UserRightsManager;
18 ilm 63
import org.openconcerto.sql.view.EditFrame;
142 ilm 64
import org.openconcerto.sql.view.EditPanel.EditMode;
18 ilm 65
import org.openconcerto.ui.DefaultGridBagConstraints;
25 ilm 66
import org.openconcerto.ui.FormLayouter;
132 ilm 67
import org.openconcerto.ui.FrameUtil;
18 ilm 68
import org.openconcerto.ui.JDate;
69
import org.openconcerto.ui.component.ITextArea;
93 ilm 70
import org.openconcerto.ui.component.InteractionMode;
18 ilm 71
import org.openconcerto.utils.ExceptionHandler;
142 ilm 72
import org.openconcerto.utils.cc.IFactory;
21 ilm 73
import org.openconcerto.utils.checks.ValidState;
18 ilm 74
 
132 ilm 75
import java.awt.Dimension;
76
import java.awt.GridBagConstraints;
77
import java.awt.GridBagLayout;
78
import java.awt.event.ActionEvent;
79
import java.awt.event.ActionListener;
80
import java.beans.PropertyChangeEvent;
81
import java.beans.PropertyChangeListener;
82
import java.sql.SQLException;
83
import java.util.ArrayList;
84
import java.util.Date;
85
import java.util.List;
86
 
87
import javax.swing.JButton;
88
import javax.swing.JCheckBox;
89
import javax.swing.JLabel;
90
import javax.swing.JOptionPane;
91
import javax.swing.JPanel;
92
import javax.swing.JScrollPane;
93
import javax.swing.JTextField;
94
import javax.swing.SwingConstants;
95
import javax.swing.SwingUtilities;
96
import javax.swing.event.DocumentEvent;
97
import javax.swing.event.DocumentListener;
98
 
99
import org.apache.commons.dbutils.handlers.ArrayListHandler;
100
 
18 ilm 101
public class AvoirClientSQLComponent extends TransfertBaseSQLComponent implements ActionListener {
102
 
73 ilm 103
    protected PanelOOSQLComponent panelGestDoc;
156 ilm 104
    private TotalPanel totalTTC;
18 ilm 105
    private JTextField textNom;
106
    private JDate date;
107
    private JUniqueTextField textNumero;
108
    private AbstractArticleItemTable table;
109
    private JCheckBox boxAdeduire = new JCheckBox(getLabelFor("A_DEDUIRE"));
110
    private ElementSQLObject eltModeRegl;
111
    private final SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT");
112
    private final SQLElement clientElt = Configuration.getInstance().getDirectory().getElement(this.tableClient);
113
    private final ElementComboBox comboClient = new ElementComboBox();
114
    private ElementComboBox comboPole = new ElementComboBox();
115
    private ElementComboBox comboCommercial = new ElementComboBox();
116
    private ElementComboBox comboVerificateur = new ElementComboBox();
117
    private final ElementComboBox comboBanque = new ElementComboBox();
142 ilm 118
    private ElementComboBox selectContact;
18 ilm 119
    private JLabel labelCompteServ;
120
    private ISQLCompteSelector compteSelService;
121
    private static final SQLTable TABLE_PREFS_COMPTE = Configuration.getInstance().getBase().getTable("PREFS_COMPTE");
122
    private static final SQLRow ROW_PREFS_COMPTE = TABLE_PREFS_COMPTE.getRow(2);
93 ilm 123
    private final boolean displayDpt;
124
    private final ElementComboBox comboDpt = new ElementComboBox();
18 ilm 125
 
126
    private JCheckBox checkCompteServiceAuto;
127
 
128
    private PropertyChangeListener listenerModeReglDefaut = new PropertyChangeListener() {
129
        public void propertyChange(PropertyChangeEvent arg0) {
73 ilm 130
            int idCli = AvoirClientSQLComponent.this.comboClient.getWantedID();
18 ilm 131
            if (idCli > 1) {
132
                SQLRow rowCli = AvoirClientSQLComponent.this.tableClient.getRow(idCli);
156 ilm 133
                if (!isFilling() && !rowCli.isForeignEmpty("ID_COMMERCIAL")) {
94 ilm 134
                    comboCommercial.setValue(rowCli.getForeignID("ID_COMMERCIAL"));
135
                }
156 ilm 136
                if (rowCli.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowCli.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
137
                    totalTTC.setCategorieComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
138
                } else {
139
                    totalTTC.setCategorieComptable(null);
140
                }
18 ilm 141
                SQLElement sqleltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
142
                int idModeRegl = rowCli.getInt("ID_MODE_REGLEMENT");
73 ilm 143
                if (!isFilling() && idModeRegl > 1 && AvoirClientSQLComponent.this.eltModeRegl.isCreated()) {
18 ilm 144
                    SQLRow rowModeRegl = sqleltModeRegl.getTable().getRow(idModeRegl);
145
                    SQLRowValues rowValsModeRegl = rowModeRegl.createUpdateRow();
146
                    rowValsModeRegl.clearPrimaryKeys();
147
                    AvoirClientSQLComponent.this.eltModeRegl.setValue(rowValsModeRegl);
148
                }
156 ilm 149
            } else {
150
                totalTTC.setCategorieComptable(null);
18 ilm 151
            }
152
        }
153
    };
19 ilm 154
    private final ElementComboBox boxTarif = new ElementComboBox();
18 ilm 155
    private PropertyChangeListener changeClientListener = new PropertyChangeListener() {
156
        public void propertyChange(PropertyChangeEvent evt) {
157
            // compteSel.removeValueListener(changeCompteListener);
158
 
73 ilm 159
            // if (AvoirClientSQLComponent.this.comboClient.getValue() != null) {
160
            Integer id = AvoirClientSQLComponent.this.comboClient.getWantedID();
161
            if (id > 1) {
19 ilm 162
 
73 ilm 163
                SQLRow row = AvoirClientSQLComponent.this.clientElt.getTable().getRow(id);
164
 
165
                final SQLField fieldForeignClient = getTable().getDBRoot().findTable("CONTACT").getField("ID_CLIENT");
166
                Where wC = new Where(fieldForeignClient, "=", SQLRow.NONEXISTANT_ID);
167
                    wC = wC.or(new Where(getTable().getDBRoot().findTable("CONTACT").getField("ID_CLIENT"), "=", id));
168
                selectContact.getRequest().setWhere(wC);
169
 
156 ilm 170
                if (row.getObject("ID_CATEGORIE_COMPTABLE") != null && !row.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
171
                    table.setRowCatComptable(row.getForeign("ID_CATEGORIE_COMPTABLE"));
172
                } else {
173
                    table.setRowCatComptable(null);
174
                }
175
 
73 ilm 176
                if (!isFilling() && comboClient.getElement().getTable().getFieldsName().contains("ID_TARIF")) {
177
 
178
                    // SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
179
                    // if (foreignRow.isUndefined() &&
180
                    // !row.getForeignRow("ID_DEVISE").isUndefined()) {
181
                    // SQLRowValues rowValsD = new SQLRowValues(foreignRow.getTable());
182
                    // rowValsD.put("ID_DEVISE", row.getObject("ID_DEVISE"));
183
                    // foreignRow = rowValsD;
184
                    //
185
                    // }
186
                    // tableBonItem.setTarif(foreignRow, true);
187
                    SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
188
                    if (!foreignRow.isUndefined() && (boxTarif.getSelectedRow() == null || boxTarif.getSelectedId() != foreignRow.getID())
189
                            && JOptionPane.showConfirmDialog(null, "Appliquer les tarifs associés au client?") == JOptionPane.YES_OPTION) {
190
                        boxTarif.setValue(foreignRow.getID());
191
                        // SaisieVenteFactureSQLComponent.this.tableFacture.setTarif(foreignRow,
192
                        // true);
193
                    } else {
194
                        boxTarif.setValue(foreignRow.getID());
19 ilm 195
                    }
73 ilm 196
                }
174 ilm 197
                if (!isFilling()) {
198
                    AvoirClientSQLComponent.this.table.setClient(row, true);
199
                }
19 ilm 200
 
73 ilm 201
            } else {
156 ilm 202
                table.setRowCatComptable(null);
73 ilm 203
                selectContact.getRequest().setWhere(Where.FALSE);
18 ilm 204
            }
73 ilm 205
            // }
18 ilm 206
        }
207
    };
208
 
209
 
73 ilm 210
    protected org.openconcerto.sql.view.list.RowValuesTable getRowValuesTable() {
211
        return this.table.getRowValuesTable();
212
 
213
    };
214
 
18 ilm 215
    @Override
216
    protected SQLRowValues createDefaults() {
217
        SQLRowValues vals = new SQLRowValues(this.getTable());
218
        vals.put("A_DEDUIRE", Boolean.TRUE);
93 ilm 219
        this.eltModeRegl.setEditable(InteractionMode.DISABLED);
18 ilm 220
        this.eltModeRegl.setCreated(false);
221
 
222
 
223
        // Selection du compte de service
224
        int idCompteVenteService = ROW_PREFS_COMPTE.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
225
        if (idCompteVenteService <= 1) {
226
            try {
227
                idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
228
            } catch (Exception e) {
229
                e.printStackTrace();
230
            }
231
        }
93 ilm 232
        vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date()));
18 ilm 233
        vals.put("MONTANT_TTC", Long.valueOf(0));
234
        vals.put("MONTANT_SERVICE", Long.valueOf(0));
235
        vals.put("MONTANT_HT", Long.valueOf(0));
236
        vals.put("MONTANT_TVA", Long.valueOf(0));
237
        vals.put("ID_COMPTE_PCE_SERVICE", idCompteVenteService);
238
 
239
        return vals;
240
    }
241
 
242
    public AvoirClientSQLComponent() {
243
        super(Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT"));
93 ilm 244
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
245
        this.displayDpt = prefs.getBoolean(GestionClientPreferencePanel.DISPLAY_CLIENT_DPT, false);
18 ilm 246
    }
247
 
248
    public void addViews() {
249
        this.setLayout(new GridBagLayout());
250
        final GridBagConstraints c = new DefaultGridBagConstraints();
73 ilm 251
        textNumero = new JUniqueTextField(16);
25 ilm 252
        // Champ Module
253
        c.gridx = 0;
254
        c.gridy++;
255
        c.gridwidth = GridBagConstraints.REMAINDER;
63 ilm 256
        final JPanel addP = ComptaSQLConfElement.createAdditionalPanel();
25 ilm 257
        this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
258
        this.add(addP, c);
259
 
260
        c.gridy++;
261
        c.gridwidth = 1;
262
 
18 ilm 263
        this.textNom = new JTextField();
264
        this.date = new JDate(true);
265
 
266
 
73 ilm 267
            this.date.addValueListener(new PropertyChangeListener() {
18 ilm 268
 
73 ilm 269
                @Override
270
                public void propertyChange(PropertyChangeEvent evt) {
271
                    fireValidChange();
93 ilm 272
                    if (!isFilling() && date.getValue() != null) {
273
                        table.setDateDevise(date.getValue());
274
                    }
73 ilm 275
                }
276
            });
277
 
278
 
18 ilm 279
        // Ligne 1: Numero
280
        this.add(new JLabel(getLabelFor("NUMERO"), SwingConstants.RIGHT), c);
281
        c.weightx = 1;
282
        c.fill = GridBagConstraints.NONE;
283
        c.gridx++;
73 ilm 284
 
18 ilm 285
        DefaultGridBagConstraints.lockMinimumSize(textNumero);
286
        this.add(this.textNumero, c);
287
 
288
        // Date
289
        c.gridx++;
290
        c.weightx = 0;
291
        c.fill = GridBagConstraints.HORIZONTAL;
292
        this.add(new JLabel("Date", SwingConstants.RIGHT), c);
293
        c.gridx++;
294
        c.weightx = 1;
295
        c.fill = GridBagConstraints.NONE;
296
        this.add(this.date, c);
297
 
298
        // Ligne 2: Libellé
299
        c.gridx = 0;
300
        c.gridy++;
301
        c.weightx = 0;
302
        c.fill = GridBagConstraints.HORIZONTAL;
303
        this.add(new JLabel(getLabelFor("NOM"), SwingConstants.RIGHT), c);
304
        c.gridx++;
305
        // c.weightx = 1;
306
        this.add(this.textNom, c);
307
 
308
        // Commercial
309
        c.gridx++;
310
        c.fill = GridBagConstraints.HORIZONTAL;
311
        c.weightx = 0;
312
        this.comboCommercial = new ElementComboBox();
313
        this.comboCommercial.setMinimumSize(this.comboCommercial.getPreferredSize());
73 ilm 314
            this.add(new JLabel(getLabelFor("ID_COMMERCIAL"), SwingConstants.RIGHT), c);
315
            c.gridx++;
316
            // c.weightx = 1;
317
            c.fill = GridBagConstraints.NONE;
318
            this.add(this.comboCommercial, c);
18 ilm 319
 
73 ilm 320
            this.addSQLObject(this.comboCommercial, "ID_COMMERCIAL");
18 ilm 321
 
322
        // Ligne 3: Motif
323
        c.fill = GridBagConstraints.HORIZONTAL;
324
        c.gridx = 0;
325
        c.gridy++;
326
        c.weightx = 0;
327
        this.add(new JLabel(getLabelFor("MOTIF"), SwingConstants.RIGHT), c);
328
        c.gridx++;
93 ilm 329
        c.gridwidth = 1;
18 ilm 330
        // c.weightx = 1;
331
 
332
        JTextField textMotif = new JTextField();
333
        this.add(textMotif, c);
334
 
94 ilm 335
        if (getTable().contains("DATE_LIVRAISON")) {
336
            JLabel labelDateLiv = new JLabel("Livraison le");
337
            c.gridx++;
338
            c.gridwidth = 1;
339
            c.weightx = 0;
340
            c.fill = GridBagConstraints.HORIZONTAL;
341
            labelDateLiv.setHorizontalAlignment(SwingConstants.RIGHT);
342
            this.add(labelDateLiv, c);
343
 
344
            c.gridx++;
345
            c.gridwidth = 1;
346
            c.weightx = 0;
347
            c.fill = GridBagConstraints.NONE;
348
            JDate dateLiv = new JDate();
349
            this.add(dateLiv, c);
350
            c.fill = GridBagConstraints.HORIZONTAL;
351
            this.addSQLObject(dateLiv, "DATE_LIVRAISON");
352
        }
353
 
18 ilm 354
        // Client
355
        c.gridx = 0;
356
        c.gridy++;
93 ilm 357
        c.weightx = 0;
18 ilm 358
        c.gridwidth = 1;
359
        this.add(new JLabel(getLabelFor("ID_CLIENT"), SwingConstants.RIGHT), c);
360
        c.gridx++;
93 ilm 361
        c.gridwidth = 1;
362
        c.weightx = 1;
18 ilm 363
        c.fill = GridBagConstraints.NONE;
364
        this.add(this.comboClient, c);
93 ilm 365
        this.addRequiredSQLObject(this.comboClient, "ID_CLIENT");
366
 
367
        if (this.displayDpt) {
368
            c.gridx++;
369
            c.gridwidth = 1;
370
            c.weightx = 0;
371
            final JLabel labelDpt = new JLabel(getLabelFor("ID_CLIENT_DEPARTEMENT"));
372
            labelDpt.setHorizontalAlignment(SwingConstants.RIGHT);
373
            c.weightx = 0;
374
            c.gridwidth = 1;
18 ilm 375
            c.fill = GridBagConstraints.HORIZONTAL;
93 ilm 376
            this.add(labelDpt, c);
18 ilm 377
 
378
            c.gridx++;
93 ilm 379
            c.gridwidth = 1;
380
            c.weightx = 0;
381
            c.weighty = 0;
18 ilm 382
            c.fill = GridBagConstraints.NONE;
93 ilm 383
            this.add(this.comboDpt, c);
384
            DefaultGridBagConstraints.lockMinimumSize(this.comboDpt);
385
            addSQLObject(this.comboDpt, "ID_CLIENT_DEPARTEMENT");
386
 
387
            comboClient.addModelListener("wantedID", new PropertyChangeListener() {
388
 
389
                @Override
390
                public void propertyChange(PropertyChangeEvent evt) {
391
                    int wantedID = comboClient.getWantedID();
392
 
393
                    if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
394
                        final SQLRow rowClient = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
395
                        comboDpt.getRequest().setWhere(new Where(comboDpt.getRequest().getPrimaryTable().getField("ID_CLIENT"), "=", rowClient.getID()));
396
                    } else {
397
                        comboDpt.getRequest().setWhere(null);
398
                    }
399
                }
400
            });
401
 
402
        }
403
 
94 ilm 404
            SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
405
            if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ADDRESS_SPEC, true)) {
93 ilm 406
 
94 ilm 407
                // Adresse spe
408
                final SQLElement adrElement = getElement().getForeignElement("ID_ADRESSE");
409
                final AddressChoiceUI addressUI = new AddressChoiceUI();
410
                addressUI.addToUI(this, c);
411
                comboClient.addModelListener("wantedID", new PropertyChangeListener() {
93 ilm 412
 
94 ilm 413
                    @Override
414
                    public void propertyChange(PropertyChangeEvent evt) {
415
                        int wantedID = comboClient.getWantedID();
416
                        System.err.println("SET WHERE ID_CLIENT = " + wantedID);
417
                        if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
418
 
132 ilm 419
                            addressUI.getComboAdrF().getRequest().setWhere(
420
                                    new Where(adrElement.getTable().getField("ID_CLIENT"), "=", wantedID).and(new Where(adrElement.getTable().getField("TYPE"), "=", AdresseType.Invoice.getId())));
421
                            addressUI.getComboAdrL().getRequest().setWhere(
422
                                    new Where(adrElement.getTable().getField("ID_CLIENT"), "=", wantedID).and(new Where(adrElement.getTable().getField("TYPE"), "=", AdresseType.Delivery.getId())));
94 ilm 423
                        } else {
424
                            addressUI.getComboAdrF().getRequest().setWhere(Where.FALSE);
425
                            addressUI.getComboAdrL().getRequest().setWhere(Where.FALSE);
426
                        }
93 ilm 427
                    }
94 ilm 428
                });
429
            }
174 ilm 430
            if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.CATEGORIE_COMPTABLE_SPEC, false)) {
431
                // cat spe
432
                final CategorieComptableChoiceUI catUI = new CategorieComptableChoiceUI();
433
                catUI.addToUI(this, c);
434
                catUI.getCombo().addModelListener("wantedID", new PropertyChangeListener() {
93 ilm 435
 
174 ilm 436
                    @Override
437
                    public void propertyChange(PropertyChangeEvent evt) {
438
                        int wantedID = catUI.getCombo().getWantedID();
439
                        if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
440
                            table.setRowCatComptable(catUI.getCombo().getElement().getTable().getRow(wantedID));
441
                        } else {
442
                            table.setRowCatComptable(null);
443
                        }
444
                    }
445
                });
446
 
447
            }
448
 
18 ilm 449
        final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
450
 
451
        // Contact
452
        c.gridx = 0;
453
        c.gridy++;
454
        c.gridwidth = 1;
93 ilm 455
        c.weightx = 0;
18 ilm 456
        c.fill = GridBagConstraints.HORIZONTAL;
457
        // c.weightx = 0;
458
        final JLabel labelContact = new JLabel(getLabelFor("ID_CONTACT"), SwingConstants.RIGHT);
459
        this.add(labelContact, c);
142 ilm 460
        this.selectContact = new ElementComboBox() {
461
            @Override
462
            protected SQLComponent createSQLComponent(EditMode mode) {
463
                final SQLComponent c = super.createSQLComponent(mode);
464
                if (mode.equals(EditMode.CREATION)) {
465
                    c.setDefaultsFactory(new IFactory<SQLRowValues>() {
18 ilm 466
 
142 ilm 467
                        @Override
468
                        public SQLRowValues createChecked() {
469
                            final SQLRowValues defaultContactRowValues = new SQLRowValues(selectContact.getRequest().getPrimaryTable());
470
                            Integer id = AvoirClientSQLComponent.this.comboClient.getWantedID();
471
                            defaultContactRowValues.put("ID_CLIENT", id);
472
                            return defaultContactRowValues;
473
                        }
474
                    });
475
                }
476
                return c;
477
            }
478
        };
18 ilm 479
        c.gridx++;
480
        c.gridwidth = 3;
93 ilm 481
        c.weightx = 1;
18 ilm 482
        this.add(selectContact, c);
73 ilm 483
        final SQLElement contactElement = getElement().getForeignElement("ID_CONTACT");
484
        selectContact.init(contactElement, contactElement.getComboRequest(true));
93 ilm 485
        selectContact.getRequest().setWhere(Where.FALSE);
18 ilm 486
        this.addView(selectContact, "ID_CONTACT");
487
 
488
 
489
 
490
        // Compte Service
491
        this.checkCompteServiceAuto = new JCheckBox(getLabelFor("COMPTE_SERVICE_AUTO"));
492
        this.addSQLObject(this.checkCompteServiceAuto, "COMPTE_SERVICE_AUTO");
493
        this.compteSelService = new ISQLCompteSelector();
494
 
495
        this.labelCompteServ = new JLabel("Compte Service");
496
        c.gridy++;
497
        c.gridx = 0;
498
        c.gridwidth = 1;
93 ilm 499
        c.weightx = 0;
18 ilm 500
        this.labelCompteServ.setHorizontalAlignment(SwingConstants.RIGHT);
501
        this.add(this.labelCompteServ, c);
502
 
503
        c.gridx++;
504
        c.gridwidth = GridBagConstraints.REMAINDER;
93 ilm 505
        c.weightx = 1;
18 ilm 506
        this.add(this.compteSelService, c);
507
 
508
        this.addRequiredSQLObject(this.compteSelService, "ID_COMPTE_PCE_SERVICE");
509
 
510
        String valServ = DefaultNXProps.getInstance().getStringProperty("ArticleService");
511
        Boolean bServ = Boolean.valueOf(valServ);
512
        if (!bServ) {
513
            this.labelCompteServ.setVisible(false);
514
            this.compteSelService.setVisible(false);
515
        }
516
 
517
        this.checkCompteServiceAuto.addActionListener(new ActionListener() {
518
            @Override
519
            public void actionPerformed(ActionEvent e) {
520
                setCompteServiceVisible(!AvoirClientSQLComponent.this.checkCompteServiceAuto.isSelected());
521
            }
522
        });
523
 
524
        // setCompteServiceVisible(!(bServ != null && !bServ.booleanValue()));
525
 
526
 
19 ilm 527
        // Tarif
528
        if (this.getTable().getFieldsName().contains("ID_TARIF")) {
529
            // TARIF
530
            c.gridy++;
531
            c.gridx = 0;
532
            c.weightx = 0;
533
            c.weighty = 0;
534
            c.gridwidth = 1;
61 ilm 535
            this.add(new JLabel("Tarif à appliquer", SwingConstants.RIGHT), c);
19 ilm 536
            c.gridx++;
537
            c.gridwidth = GridBagConstraints.REMAINDER;
538
 
539
            c.weightx = 1;
540
            this.add(boxTarif, c);
541
            this.addView(boxTarif, "ID_TARIF");
542
            boxTarif.addValueListener(new PropertyChangeListener() {
543
 
544
                @Override
545
                public void propertyChange(PropertyChangeEvent evt) {
546
                    table.setTarif(boxTarif.getSelectedRow(), false);
547
                }
548
            });
549
        }
550
 
18 ilm 551
        // Table
552
            this.table = new AvoirItemTable();
553
        c.gridx = 0;
554
        c.gridy++;
555
        c.fill = GridBagConstraints.BOTH;
556
        c.gridheight = 1;
557
        c.gridwidth = GridBagConstraints.REMAINDER;
558
        c.weighty = 1;
559
        // c.weightx = 0;
560
        this.add(this.table, c);
561
        this.addView(this.table.getRowValuesTable(), "");
562
 
563
        // Panel du bas
564
        final JPanel panelBottom = getBottomPanel();
565
        c.gridy++;
566
        c.weighty = 0;
567
        this.add(panelBottom, c);
568
 
569
        // Infos
570
 
571
        c.gridheight = 1;
572
        c.gridx = 0;
573
        c.gridy++;
574
        this.add(new JLabel(getLabelFor("INFOS")), c);
575
 
576
        c.gridy++;
577
        c.fill = GridBagConstraints.BOTH;
578
        c.weighty = 0;
579
        c.gridwidth = 4;
580
        ITextArea infos = new ITextArea(4, 4);
41 ilm 581
        infos.setBorder(null);
18 ilm 582
        JScrollPane scrollPane = new JScrollPane(infos);
583
        DefaultGridBagConstraints.lockMinimumSize(scrollPane);
584
        this.add(scrollPane, c);
585
 
586
        //
587
        // Impression
73 ilm 588
        this.panelGestDoc = new PanelOOSQLComponent(this);
18 ilm 589
        c.fill = GridBagConstraints.NONE;
590
        c.gridy++;
591
        c.anchor = GridBagConstraints.EAST;
592
        this.add(panelGestDoc, c);
593
 
594
        this.addSQLObject(this.textNom, "NOM");
73 ilm 595
        if (getTable().contains("INFOS")) {
596
            this.addSQLObject(infos, "INFOS");
597
        }
18 ilm 598
        this.addSQLObject(this.boxAdeduire, "A_DEDUIRE");
599
        this.addSQLObject(textMotif, "MOTIF");
600
 
601
        this.addRequiredSQLObject(this.textNumero, "NUMERO");
602
        this.addRequiredSQLObject(this.date, "DATE");
603
        this.boxAdeduire.addActionListener(this);
604
 
73 ilm 605
        this.comboClient.addModelListener("wantedID", this.listenerModeReglDefaut);
606
        this.comboClient.addModelListener("wantedID", this.changeClientListener);
18 ilm 607
        DefaultGridBagConstraints.lockMinimumSize(comboClient);
608
        DefaultGridBagConstraints.lockMinimumSize(this.comboBanque);
609
        DefaultGridBagConstraints.lockMinimumSize(comboCommercial);
610
 
611
    }
612
 
613
    private JPanel getBottomPanel() {
614
 
615
        // UI
616
 
617
        final JPanel panel = new JPanel(new GridBagLayout());
618
        panel.setOpaque(false);
619
        final GridBagConstraints c = new DefaultGridBagConstraints();
620
        c.anchor = GridBagConstraints.NORTHWEST;
621
        c.weightx = 1;
622
        // Colonne 1
623
        this.boxAdeduire.setOpaque(false);
624
        this.boxAdeduire.setMinimumSize(new Dimension(430, this.boxAdeduire.getPreferredSize().height));
625
        this.boxAdeduire.setPreferredSize(new Dimension(430, this.boxAdeduire.getPreferredSize().height));
626
        panel.add(this.boxAdeduire, c);
627
        this.addView("ID_MODE_REGLEMENT", DEC + ";" + SEP);
628
        this.eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT");
629
 
630
        c.gridy++;
631
        c.fill = GridBagConstraints.NONE;
632
        c.weighty = 1;
633
        this.eltModeRegl.setOpaque(false);
634
        panel.add(this.eltModeRegl, c);
635
 
636
        // Colonne 2 : port et remise
637
 
638
        final JPanel panelPortEtRemise = new JPanel();
639
        panelPortEtRemise.setOpaque(false);
640
        panelPortEtRemise.setLayout(new GridBagLayout());
641
 
642
        final GridBagConstraints cFrais = new DefaultGridBagConstraints();
643
 
644
        DeviseField textPortHT = new DeviseField(5);
645
        DeviseField textRemiseHT = new DeviseField(5);
646
 
647
        // Frais de port
648
        cFrais.gridheight = 1;
649
        cFrais.fill = GridBagConstraints.VERTICAL;
650
        cFrais.weighty = 1;
651
        cFrais.gridx = 1;
652
 
67 ilm 653
        // FIXME implémenter la remise et les port pour les avoirs
18 ilm 654
        JLabel labelPortHT = new JLabel(getLabelFor("PORT_HT"));
655
        labelPortHT.setHorizontalAlignment(SwingConstants.RIGHT);
656
        cFrais.gridy++;
67 ilm 657
        // panelPortEtRemise.add(labelPortHT, cFrais);
18 ilm 658
        cFrais.gridx++;
659
        DefaultGridBagConstraints.lockMinimumSize(textPortHT);
67 ilm 660
        // panelPortEtRemise.add(textPortHT, cFrais);
18 ilm 661
 
662
        // Remise
663
        JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
664
        labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
665
        cFrais.gridy++;
666
        cFrais.gridx = 1;
67 ilm 667
        // panelPortEtRemise.add(labelRemiseHT, cFrais);
18 ilm 668
        cFrais.gridx++;
669
        DefaultGridBagConstraints.lockMinimumSize(textRemiseHT);
67 ilm 670
        // panelPortEtRemise.add(textRemiseHT, cFrais);
18 ilm 671
        cFrais.gridy++;
672
 
673
        c.gridx++;
674
        c.gridy = 0;
675
        c.gridheight = 2;
676
        c.weightx = 0;
677
        c.fill = GridBagConstraints.HORIZONTAL;
678
        c.anchor = GridBagConstraints.NORTHWEST;
679
        panel.add(panelPortEtRemise, c);
680
 
681
        // Colonne 3 : totaux
682
        final DeviseField fieldHT = new DeviseField();
142 ilm 683
        final DeviseField fieldEco = new DeviseField();
18 ilm 684
        final DeviseField fieldTVA = new DeviseField();
685
        final DeviseField fieldService = new DeviseField();
686
        final DeviseField fieldTTC = new DeviseField();
687
        // SQL
688
        addSQLObject(textPortHT, "PORT_HT");
19 ilm 689
        final DeviseField fieldDevise = new DeviseField();
690
        if (getTable().getFieldsName().contains("T_DEVISE"))
691
            addSQLObject(fieldDevise, "T_DEVISE");
18 ilm 692
        addSQLObject(textRemiseHT, "REMISE_HT");
142 ilm 693
        addSQLObject(fieldEco, "T_ECO_CONTRIBUTION");
18 ilm 694
        addRequiredSQLObject(fieldHT, "MONTANT_HT");
695
        addRequiredSQLObject(fieldTVA, "MONTANT_TVA");
696
        addRequiredSQLObject(fieldTTC, "MONTANT_TTC");
697
        addRequiredSQLObject(fieldService, "MONTANT_SERVICE");
698
        //
19 ilm 699
        JTextField poids = new JTextField();
700
        if (getTable().getFieldsName().contains("T_POIDS"))
701
            addSQLObject(poids, "T_POIDS");
156 ilm 702
        this.totalTTC = new TotalPanel(this.table, fieldEco, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, null, fieldDevise, poids, null);
18 ilm 703
        totalTTC.setOpaque(false);
704
        c.gridx++;
705
        c.gridy = 0;
706
        c.gridheight = 2;
707
        c.fill = GridBagConstraints.BOTH;
708
        panel.add(totalTTC, c);
709
 
710
        // Listeners
711
        textPortHT.getDocument().addDocumentListener(new DocumentListener() {
712
            public void changedUpdate(DocumentEvent e) {
713
                totalTTC.updateTotal();
714
            }
715
 
716
            public void removeUpdate(DocumentEvent e) {
717
                totalTTC.updateTotal();
718
            }
719
 
720
            public void insertUpdate(DocumentEvent e) {
721
                totalTTC.updateTotal();
722
            }
723
        });
724
 
725
        textRemiseHT.getDocument().addDocumentListener(new DocumentListener() {
726
            public void changedUpdate(DocumentEvent e) {
727
                totalTTC.updateTotal();
728
            }
729
 
730
            public void removeUpdate(DocumentEvent e) {
731
                totalTTC.updateTotal();
732
            }
733
 
734
            public void insertUpdate(DocumentEvent e) {
735
                totalTTC.updateTotal();
736
            }
737
        });
738
        return panel;
739
    }
740
 
21 ilm 741
    @Override
742
    public synchronized ValidState getValidState() {
743
        final ValidState selfState;
18 ilm 744
        final Date value = this.date.getValue();
21 ilm 745
        if (value != null && value.after(SocieteCommonSQLElement.getDateDebutExercice())) {
746
            selfState = ValidState.getTrueInstance();
747
        } else {
748
            selfState = ValidState.createCached(false, "La date est incorrecte, cette période est cloturée.");
749
        }
750
        return super.getValidState().and(selfState);
18 ilm 751
    }
752
 
753
    private void setCompteServiceVisible(boolean b) {
754
        this.compteSelService.setVisible(b);
755
        this.labelCompteServ.setVisible(b);
756
    }
757
 
758
    private String getInitialesFromVerif(SQLRow row) {
759
        String s = "";
760
 
761
        if (row != null) {
762
            String prenom = row.getString("PRENOM");
763
            if (prenom != null && prenom.length() > 0) {
764
                s += prenom.toUpperCase().charAt(0);
765
            }
766
            String nom = row.getString("NOM");
767
            if (nom != null && nom.length() > 0) {
768
                s += nom.toUpperCase().charAt(0);
769
            }
770
        }
771
 
772
        return s;
773
    }
774
 
775
    private void createCompteServiceAuto(int id) {
776
        SQLRow rowPole = this.comboPole.getSelectedRow();
777
        SQLRow rowVerif = this.comboVerificateur.getSelectedRow();
778
        String verifInitiale = getInitialesFromVerif(rowVerif);
779
        int idCpt = ComptePCESQLElement.getId("706" + rowPole.getString("CODE") + verifInitiale, "Service " + rowPole.getString("NOM") + " " + rowVerif.getString("NOM"));
780
        SQLRowValues rowVals = this.getTable().getRow(id).createEmptyUpdateRow();
781
        rowVals.put("ID_COMPTE_PCE_SERVICE", idCpt);
782
        try {
783
            rowVals.update();
784
        } catch (SQLException e) {
785
            e.printStackTrace();
786
        }
787
    }
788
 
789
    @Override
790
    public int insert(SQLRow order) {
791
 
792
        int id = getSelectedID();
793
        final SQLTable tableNum = this.getTable().getBase().getTable("NUMEROTATION_AUTO");
794
        if (this.textNumero.checkValidation()) {
795
 
796
            id = super.insert(order);
797
 
73 ilm 798
            try {
799
                this.table.updateField("ID_AVOIR_CLIENT", id);
800
                final SQLRow row = getTable().getRow(id);
18 ilm 801
 
73 ilm 802
                // incrémentation du numéro auto
93 ilm 803
                if (NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), row.getDate("DATE").getTime()).equalsIgnoreCase(this.textNumero.getText().trim())) {
73 ilm 804
                    SQLRowValues rowVals = new SQLRowValues(tableNum);
93 ilm 805
                    String label = NumerotationAutoSQLElement.getLabelNumberFor(getElement().getClass());
73 ilm 806
                    int val = tableNum.getRow(2).getInt(label);
807
                    val++;
808
                    rowVals.put(label, Integer.valueOf(val));
18 ilm 809
 
73 ilm 810
                    try {
811
                        rowVals.update(2);
812
                    } catch (SQLException e) {
813
 
814
                        e.printStackTrace();
815
                    }
18 ilm 816
                }
817
 
73 ilm 818
                SQLRowValues rowVals2 = row.createUpdateRow();
819
                Long l = rowVals2.getLong("MONTANT_SOLDE");
820
                Long l2 = rowVals2.getLong("MONTANT_TTC");
18 ilm 821
 
73 ilm 822
                rowVals2.put("MONTANT_RESTANT", l2 - l);
18 ilm 823
 
824
                rowVals2.update();
825
 
83 ilm 826
                // updateStock(id);
132 ilm 827
                final int idFinal = id;
828
                ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
18 ilm 829
 
132 ilm 830
                    @Override
831
                    public void run() {
832
                        try {
833
                            updateStock(idFinal);
834
                        } catch (Exception e) {
835
                            ExceptionHandler.handle("Update error", e);
836
                        }
837
                    }
838
                });
839
 
93 ilm 840
                GenerationMvtAvoirClient gen = new GenerationMvtAvoirClient(row);
73 ilm 841
                gen.genereMouvement();
18 ilm 842
 
73 ilm 843
                // generation du document
844
                createAvoirClient(row);
132 ilm 845
 
846
                useAvoir(row);
73 ilm 847
            } catch (Exception e) {
848
                ExceptionHandler.handle("Erreur lors de la création de l'avoir", e);
849
            }
18 ilm 850
        } else {
851
            ExceptionHandler.handle("Impossible de modifier, numéro d'avoir existant.");
852
            Object root = SwingUtilities.getRoot(this);
853
            if (root instanceof EditFrame) {
854
                EditFrame frame = (EditFrame) root;
855
                frame.getPanel().setAlwaysVisible(true);
856
            }
857
        }
858
        return id;
859
    }
860
 
73 ilm 861
    protected void createAvoirClient(final SQLRow row) {
25 ilm 862
 
863
        final AvoirClientXmlSheet bSheet = new AvoirClientXmlSheet(row);
864
        try {
865
            bSheet.createDocumentAsynchronous();
73 ilm 866
            bSheet.showPrintAndExportAsynchronous(panelGestDoc.isVisualisationSelected(), panelGestDoc.isImpressionSelected(), true);
25 ilm 867
        } catch (Exception e) {
868
            ExceptionHandler.handle("Impossible de créer l'avoir", e);
869
        }
870
 
871
    }
872
 
132 ilm 873
    public void useAvoir(final SQLRowAccessor r) {
874
        if (r.getBoolean("A_DEDUIRE") && r.getReferentRows(getTable().getTable("SAISIE_VENTE_FACTURE")).size() == 0) {
875
            JPanel p = new JPanel(new GridBagLayout());
876
            GridBagConstraints c = new DefaultGridBagConstraints();
877
            c.gridwidth = GridBagConstraints.REMAINDER;
878
            p.add(new JLabel("Voulez appliquer cet avoir sur une facture existante?"), c);
879
            c.gridy++;
880
            c.gridwidth = 1;
881
            p.add(new JLabel("Appliquer l'avoir sur la facture : "), c);
882
            c.gridx++;
883
            final SQLRequestComboBox box = new SQLRequestComboBox();
884
            final ComboSQLRequest comboRequest = getElement().getDirectory().getElement("SAISIE_VENTE_FACTURE").getComboRequest(true);
885
            Where w = new Where(comboRequest.getPrimaryTable().getField("ID_AVOIR_CLIENT"), "=", getTable().getUndefinedID());
886
            w = w.and(new Where(comboRequest.getPrimaryTable().getField("ID_CLIENT"), "=", r.getForeignID("ID_CLIENT")));
887
            comboRequest.setWhere(w);
888
            box.uiInit(comboRequest);
889
            p.add(box, c);
890
            c.gridy++;
891
            c.gridx = 0;
892
            final JButton buttonApply = new JButton("Appliquer");
893
            JButton buttonAnnuler = new JButton("Fermer");
894
            p.add(buttonApply, c);
895
            buttonApply.setEnabled(false);
896
            box.addValueListener(new PropertyChangeListener() {
897
 
898
                @Override
899
                public void propertyChange(PropertyChangeEvent evt) {
900
                    buttonApply.setEnabled(box.getSelectedRow() != null);
901
 
902
                }
903
            });
904
            c.gridx++;
905
            p.add(buttonAnnuler, c);
906
            final PanelFrame f = new PanelFrame(p, "Affection d'un avoir client");
907
 
908
            buttonAnnuler.addActionListener(new ActionListener() {
909
 
910
                @Override
911
                public void actionPerformed(ActionEvent e) {
912
                    f.dispose();
913
                }
914
            });
915
 
916
            buttonApply.addActionListener(new ActionListener() {
917
 
918
                @Override
919
                public void actionPerformed(ActionEvent e) {
920
                    SQLRow rowFacture = box.getSelectedRow();
921
                    long ttc = rowFacture.getLong("T_TTC");
922
                    long totalAvoirTTC = r.getLong("MONTANT_TTC");
923
                    final long totalSolde = r.getLong("MONTANT_SOLDE");
924
                    long totalAvoir = totalAvoirTTC - totalSolde;
925
 
926
                    long totalAvoirApplique = 0;
927
                    long netAPayer = ttc - totalAvoir;
928
                    if (netAPayer < 0) {
929
                        netAPayer = 0;
930
                        totalAvoirApplique = ttc;
931
                    } else {
932
                        totalAvoirApplique = totalAvoir;
933
                    }
934
 
935
                    final SQLRowValues createEmptyUpdateRow = rowFacture.createEmptyUpdateRow();
936
                    createEmptyUpdateRow.put("ID_AVOIR_CLIENT", r.getID());
937
                    createEmptyUpdateRow.put("NET_A_PAYER", netAPayer);
938
                    createEmptyUpdateRow.put("T_AVOIR_TTC", totalAvoirApplique);
939
                    try {
940
                        rowFacture = createEmptyUpdateRow.commit();
941
 
942
                        long restant = totalAvoirTTC - totalAvoirApplique;
943
 
944
                        SQLRowValues rowVals = r.createEmptyUpdateRow();
945
                        final long l2 = ttc - restant;
946
                        // Soldé
947
                        if (l2 >= 0) {
948
                            rowVals.put("SOLDE", Boolean.TRUE);
949
                            rowVals.put("MONTANT_SOLDE", totalAvoirTTC);
950
                            rowVals.put("MONTANT_RESTANT", 0);
951
                        } else {
952
                            // Il reste encore de l'argent pour l'avoir
953
                            final long m = totalSolde + ttc;
954
                            rowVals.put("MONTANT_SOLDE", m);
955
                            rowVals.put("MONTANT_RESTANT", totalAvoirTTC - m);
956
                        }
957
 
958
                        rowVals.update();
177 ilm 959
                        List<SQLRow> rowEch = rowFacture.getReferentRows(rowFacture.getTable().getTable("ECHEANCE_CLIENT"));
960
                        for (SQLRow sqlRow : rowEch) {
961
                            if (!sqlRow.getBoolean("REG_COMPTA") && !sqlRow.getBoolean("REGLE")) {
962
                                // update echeance
963
                                SQLRowValues createEmptyUpdateRow2 = sqlRow.createEmptyUpdateRow();
964
                                createEmptyUpdateRow2.put("MONTANT", Math.max(0, sqlRow.getLong("MONTANT") - totalAvoir));
965
                                createEmptyUpdateRow2.commit();
966
                                break;
967
                            }
968
                        }
132 ilm 969
                    } catch (SQLException e1) {
970
                        ExceptionHandler.handle("Erreur lors de l'affection de l'avoir sur la facture!", e1);
971
                    } finally {
972
                        f.dispose();
973
                    }
974
 
975
                }
976
            });
977
            SwingUtilities.invokeLater(new Runnable() {
978
 
979
                @Override
980
                public void run() {
981
 
982
                    FrameUtil.showPacked(f);
983
                }
984
 
985
            });
986
        }
987
    }
988
 
18 ilm 989
    @Override
990
    public void select(SQLRowAccessor r) {
991
        if (r != null) {
992
 
993
            // Les contacts sont filtrés en fonction du client (ID_AFFAIRE.ID_CLIENT), donc si
994
            // l'ID_CONTACT est changé avant ID_AFFAIRE le contact ne sera pas présent dans la combo
995
            // => charge en deux fois les valeurs
132 ilm 996
            final SQLRowValues rVals = r.asRowValues().deepCopy();
18 ilm 997
            final SQLRowValues vals = new SQLRowValues(r.getTable());
998
 
999
            vals.load(rVals, createSet("ID_CLIENT"));
1000
            // vals a besoin de l'ID sinon incohérence entre ID_AFFAIRE et ID (eg for
1001
            // reloadTable())
1002
            // ne pas supprimer l'ID de rVals pour qu'on puisse UPDATE
1003
            vals.setID(rVals.getID());
1004
            super.select(vals);
1005
            rVals.remove("ID_CLIENT");
1006
            super.select(rVals);
156 ilm 1007
 
1008
 
18 ilm 1009
        } else {
1010
            super.select(r);
1011
        }
73 ilm 1012
 
18 ilm 1013
    }
1014
 
1015
    @Override
1016
    public void update() {
1017
        if (this.textNumero.checkValidation()) {
1018
            super.update();
73 ilm 1019
            try {
1020
                this.table.updateField("ID_AVOIR_CLIENT", getSelectedID());
18 ilm 1021
 
73 ilm 1022
                // On efface les anciens mouvements de stocks
1023
                SQLRow row = getTable().getRow(getSelectedID());
1024
                SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
1025
                SQLSelect sel = new SQLSelect(eltMvtStock.getTable().getBase());
1026
                sel.addSelect(eltMvtStock.getTable().getField("ID"));
1027
                Where w = new Where(eltMvtStock.getTable().getField("IDSOURCE"), "=", row.getID());
1028
                Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
1029
                sel.setWhere(w.and(w2));
18 ilm 1030
 
73 ilm 1031
                List l = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
1032
                if (l != null) {
1033
                    for (int i = 0; i < l.size(); i++) {
1034
                        Object[] tmp = (Object[]) l.get(i);
18 ilm 1035
                        eltMvtStock.archive(((Number) tmp[0]).intValue());
1036
                    }
1037
                }
1038
 
73 ilm 1039
                SQLRowValues rowVals2 = getTable().getRow(getSelectedID()).createUpdateRow();
1040
                Long l2 = rowVals2.getLong("MONTANT_SOLDE");
1041
                Long l3 = rowVals2.getLong("MONTANT_TTC");
18 ilm 1042
 
73 ilm 1043
                rowVals2.put("MONTANT_RESTANT", l3 - l2);
18 ilm 1044
                rowVals2.update();
1045
 
73 ilm 1046
                // On met à jour le stock
83 ilm 1047
                // updateStock(getSelectedID());
132 ilm 1048
                final int idFinal = getSelectedID();
1049
                ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
18 ilm 1050
 
132 ilm 1051
                    @Override
1052
                    public void run() {
1053
                        try {
1054
                            // Mise à jour du stock
1055
                            updateStock(idFinal);
1056
                        } catch (Exception e) {
1057
                            ExceptionHandler.handle("Update error", e);
1058
                        }
1059
                    }
1060
                });
1061
 
73 ilm 1062
                int idMvt = row.getInt("ID_MOUVEMENT");
18 ilm 1063
 
73 ilm 1064
                // on supprime tout ce qui est lié à la facture d'avoir
1065
                System.err.println("Archivage des fils");
1066
                EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE");
1067
                eltEcr.archiveMouvementProfondeur(idMvt, false);
18 ilm 1068
 
93 ilm 1069
                GenerationMvtAvoirClient gen = new GenerationMvtAvoirClient(row, idMvt);
73 ilm 1070
                gen.genereMouvement();
18 ilm 1071
 
73 ilm 1072
                createAvoirClient(row);
132 ilm 1073
 
1074
                useAvoir(row);
73 ilm 1075
            } catch (Exception e) {
1076
                ExceptionHandler.handle("Erreur de mise à jour de l'avoir", e);
1077
            }
18 ilm 1078
        } else {
1079
            ExceptionHandler.handle("Impossible de modifier, numéro d'avoir existant.");
1080
            Object root = SwingUtilities.getRoot(this);
1081
            if (root instanceof EditFrame) {
1082
                EditFrame frame = (EditFrame) root;
1083
                frame.getPanel().setAlwaysVisible(true);
1084
            }
1085
            return;
1086
        }
1087
    }
1088
 
132 ilm 1089
    // // Su^prression de la methode, retour de marchandise à gérer avec les Mouvements de stocks
83 ilm 1090
    // protected String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) {
1091
    // return "Avoir client N°" + row.getString("NUMERO");
1092
    // }
1093
    //
1094
    // /**
1095
    // * Mise à jour des stocks pour chaque article composant la facture d'avoir
1096
    // *
1097
    // * @throws SQLException
1098
    // */
1099
    // private void updateStock(int id) throws SQLException {
1100
    //
1101
    // MouvementStockSQLElement mvtStock = (MouvementStockSQLElement)
1102
    // Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
1103
    // mvtStock.createMouvement(getTable().getRow(id), getTable().getTable("AVOIR_CLIENT_ELEMENT"),
1104
    // new StockLabel() {
1105
    // @Override
1106
    // public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
1107
    // return getLibelleStock(rowOrigin, rowElt);
1108
    // }
1109
    // }, true, true);
1110
    //
1111
    // }
132 ilm 1112
    protected String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) {
1113
        return "Avoir client N°" + row.getString("NUMERO");
1114
    }
61 ilm 1115
 
132 ilm 1116
    /**
1117
     * Mise à jour des stocks pour chaque article composant du bon
1118
     *
1119
     * @throws SQLException
1120
     */
1121
    private void updateStock(int id) throws SQLException {
1122
 
1123
        SQLRow row = getTable().getRow(id);
1124
        final List<SQLRow> referentRows = row.getReferentRows(getTable().getTable("AVOIR_CLIENT_ELEMENT"));
1125
        final List<SQLRow> effectiveRows = new ArrayList<SQLRow>();
1126
        for (SQLRow sqlRow : referentRows) {
1127
            if (sqlRow.getBoolean("RETOUR_STOCK")) {
1128
                effectiveRows.add(sqlRow);
1129
            }
1130
        }
1131
        if (effectiveRows.size() > 0) {
1132
            StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() {
1133
 
1134
                @Override
1135
                public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
1136
 
1137
                    return getLibelleStock(rowOrigin, rowElt);
1138
                }
1139
            }, row, effectiveRows, TypeStockUpdate.RETOUR_AVOIR_CLIENT);
1140
 
1141
            stockUpdater.update();
1142
        }
1143
 
1144
    }
1145
 
18 ilm 1146
    public void actionPerformed(ActionEvent e) {
1147
        if (e.getSource() == this.boxAdeduire) {
1148
            if (this.eltModeRegl != null) {
93 ilm 1149
                boolean b = this.boxAdeduire.isSelected();
1150
                this.eltModeRegl.setEditable((!b) ? InteractionMode.READ_WRITE : InteractionMode.DISABLED);
1151
                this.eltModeRegl.setCreated(!b);
18 ilm 1152
            }
1153
        }
1154
    }
93 ilm 1155
 
1156
    @Override
1157
    protected void refreshAfterSelect(SQLRowAccessor rSource) {
1158
        table.setDateDevise(date.getValue());
1159
    }
18 ilm 1160
}