OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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