OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

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