OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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